package com.qire.antsrouter.intercept;

import com.qire.antscore.common.AntsThreadBuilder;
import com.qire.antsrouter.card.FloorCard;
import com.qire.antsrouter.utils.CancelableCountDownLatch;

import java.util.List;
import java.util.concurrent.TimeUnit;

//NavigationInterceptor
public class Interceptor implements Runnable {


    private final FloorCard postcard;
    private final List<InterceptRules> interceptorList;
    private final CancelableCountDownLatch countDownLatch;

    private int index = 0;

    public Interceptor(final FloorCard postcard,List<InterceptRules> interceptorList) {
        this.postcard = postcard;
        this.interceptorList = interceptorList;
        this.countDownLatch = new CancelableCountDownLatch(interceptorList.size());
    }

    public void onInterceptions() {
        AntsThreadBuilder.defaultExecutor().execute(this);
    }

    @Override
    public void run() {
        this.index = 0;
        InterceptRules iInterceptor = interceptorList.get(index);
        iInterceptor.process(postcard,this);

        try {
            countDownLatch.await(300, TimeUnit.SECONDS);
            if (countDownLatch.getCount() > 0) {
                    // 拦截器超时
                    postcard.onInterrupt("拦截器处理超时");
//            }else if(AssertUtils.notEmpty(countDownLatch.getMsg())){
            } else if (countDownLatch.isCancel()){
                    // 拦截
                    postcard.onInterrupt(countDownLatch.getMsg());
            } else {
                // 放行
                postcard.onNavigation();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    /**
     * 未拦截，走正常流程
     */
    public void onNext() {
//            for(InterceptRules rules : interceptorList){
//                rules.process(postcard);
//            }

        countDownLatch.countDown();
        index++;
        if(index >= interceptorList.size()) {
            return;
        }
        InterceptRules iInterceptor = interceptorList.get(index);
        iInterceptor.process(postcard,this);
    }

    /**
     * 拦截器拦截成功，中断流程
     */
    public void onInterrupt(String interruptMsg) {
        countDownLatch.cancel(interruptMsg);
    }

}
